/*
 * Copyright 2010
 * Jairou Software Organization
 * All Rights Reserved.
 * 
 * This software is the proprietary 
 * information of Roger Ramia
 * and the Jairou Software Organization 
 * Use is subject to license terms.
 * 
 * For licensing information please visit
 * http://www.jairou.org/license
 * 
 * @author Roger Ramia
 */
package org.jairou.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.jairou.core.Functions;
import org.jairou.core.XML;
 

/**
 * Place holder for web application startup 
 * and application context change event
 * handling
 *  
 * @author - Roger Ramia
 */
public final class ApplicationListener
implements ServletContextListener, ServletContextAttributeListener {
	
	private ServletContext app;

	/**
	 * Not currently implemented
	 */
	public void attributeAdded (ServletContextAttributeEvent scae) {
		System.out.println("An attribute was added to the ServletContext");
	}

	/**
	 * Not currently implemented
	 */
	public void attributeRemoved (ServletContextAttributeEvent scae) {
		System.out.println("An attribute was removed from the ServletContext");
	}

	/**
	 * Not currently implemented
	 */
	public void attributeReplaced (ServletContextAttributeEvent scae) {
		System.out.println("An attribute was replaced in the ServletContext");
	}
	
	/**
	 * Not currently implemented
	 */
	public void contextDestroyed(ServletContextEvent event) {
		try {
			this.app = null;
		}
		finally {
			System.out.println("Jairou stopped");
		}
	}

	/**
	 * Simply calls init on the XML object
	 * with the specified config-root directory
	 * defined in web.xml
	 * <br/>
	 * Use the following configuration in web.xml to specify
	 * the config-root xml directory
	 * <pre>{@code
	 * <context-param>
	 * 	  <param-name>config-root</param-name>
	 * 	  <param-value>/path/to/config/directory/</param-value>
	 * </context-param>
	 * }</pre>	
	 */
	
	public void contextInitialized(ServletContextEvent event) {
		try {		
			Map ctx = new HashMap();
			this.app = event.getServletContext();
			String root = this.app.getInitParameter("config-root");
			XML.init(root);
			ctx.put(Web.APPLICATION_SCOPE_KEY, this.app);
			Web.loadData("startup", ctx);	
			Functions.schedule("timers", ctx);
			System.out.println("Jairou running...");
		} 
		catch (Throwable t) {
			t.printStackTrace();
		}
	}
}